const Qs = require("querystring");
const axios = require("axios");
import { Toast } from "vant";
import hub, { SERVICE_EXCEPTION, TIMEOUT } from "./hub";

const http = axios.create({
  baseURL: window.path,
  timeout: 30000,
  headers: {
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
  },
  transformRequest: params => Qs.stringify(params)
});

export default http;

//拦截请求
http.interceptors.request.use(config => {
  // 处理config
  return config;
});

//拦截响应
http.interceptors.response.use(
  // 成功 : err.code >=200 || err.code <=300
  function(res) {
    const body = res.data;

    if (body.status != 1) {
      if (body.msg) {
        Toast.fail(`出现错误: ${body.msg}`);
      }
      return Promise.reject();
    }

    //处理服务器返回的数据
    return Promise.resolve(body.data);
  },

  // 失败: status > 300
  function(err) {
    if (err.code === "ECONNABORTED") {
      Toast("加载超时，请稍后再试");
    }
    if (err.response) {
      const res = err.response;
      console.log(res.status); // 404, 500...
      if (res.status == "404") {
        Toast("网络连接失败，请检查网络设置");
      }
      if (res.status == "500") {
        Toast("服务器异常,请稍后再试");
      }
    }
    return Promise.reject(err);
  }
);
